//
//  NSFileManager+SupportDirectory.m
//  Oos4ios
//
//  Created by Pablo Gonzalez on 3/18/11.
//  Copyright 2011 11870.com. All rights reserved.
//

#import "SupportDirectory.h"


@implementation SupportDirectory

+ (NSString *) findOrCreateDirectory:(NSSearchPathDirectory)searchPathDirectory 
							inDomain:(NSSearchPathDomainMask)domainMask 
				 appendPathComponent:(NSString *)appendComponent 
							   error:(NSError **)errorOut
{
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
	// Search for the path
    NSArray* paths = NSSearchPathForDirectoriesInDomains(
														 searchPathDirectory,
														 domainMask,
														 YES);
    if ([paths count] == 0)
    {
        // *** creation and return of error object omitted for space
        return nil;
    }
	
    // Normally only need the first path
    NSString *resolvedPath = [paths objectAtIndex:0];
    
    if (appendComponent)
    {
        resolvedPath = [resolvedPath
						stringByAppendingPathComponent:appendComponent];
    }
    
    // Check if the path exists
    BOOL exists;
    BOOL isDirectory;
    exists = [manager fileExistsAtPath:resolvedPath
                           isDirectory:&isDirectory];
    if (!exists || !isDirectory)
    {
        if (exists)
        {
            // *** creation and return of error object omitted for space
            return nil;
        }
		
        // Create the path if it doesn't exist
        NSError *error;
        BOOL success = [manager createDirectoryAtPath:resolvedPath
                          withIntermediateDirectories:YES
                                           attributes:nil
                                                error:&error];
        if (!success) 
        {
            if (errorOut)
            {
                *errorOut = error;
            }
            return nil;
        }
    }
    
    if (errorOut)
    {
        *errorOut = nil;
    }
    return resolvedPath;
}

+ (NSString *)applicationSupportDirectory
{
    NSString *executableName =
	[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleExecutable"];
    NSError *error;
    NSString *result =
	[self
	 findOrCreateDirectory:NSApplicationSupportDirectory
	 inDomain:NSUserDomainMask
	 appendPathComponent:executableName
	 error:&error];
    if (error)
    {
        NSLog(@"Unable to find or create application support directory:\n%@", error);
    }
    return result;
}

@end
